// === uuAltCSS.imports ===
// depend: uuMeta, uuMeta.url, uuAltCSS, uuMeta.codec, uuMeta.ajax
/*
uuAltCSS.imports() - return "dirty CSS"
 */
(function() {
var _imports, // inner namespace
    _mm = uuMeta,
    _ajax = _mm.ajax,
    _url = _mm.url,
    _ie = _mm.ie,
    _win = window,
    _doc = document,
    _cache = {}, // import cache { url: cssText }
    _codec = ((_win.UUALTCSS_DECODE_DATAURI || 0)
                && _mm.codec) ? _mm.codec.dataURI : 0,
    DATA_SCHEME_CSS = /^data\:text\/css[;,]/,
    MEMENTO = "uuAltCSSMemento",
    COMMENT = /\/\*[^*]*\*+([^\/][^*]*\*+)*\//g,
    IMPORTS =
        /@import\s*(?:url)?[\("']+\s*([\w\/.+-]+)\s*["'\)]+\s*([\w]+)?\s*;/g;

// uuAltCSS._imports - Import CSS
_imports = function() { // @return String: "dirty CSS"
  function imports(css, absdir) { // @import
    return css.replace(COMMENT, "").
               replace(IMPORTS, function(m, url, media) {
      var v = _url.abs(url, absdir);
      return imports(_ajax.sync(v), _url.dir(v));
    });
  }

  var rv = [], absdir = _url.abs("."), href, hash, dstr,
      node = _mm.toArray(_doc.styleSheets), v, w, i = 0,
      prop1 = _ie ? "owningElement" : "ownerNode",
      prop2 = _ie ? MEMENTO : "textContent";

  while ( (v = node[i++]) ) {
    if (!v.disabled) {
      href = v.href || "";
      if (!DATA_SCHEME_CSS.test(href)) { // ignore data:text/css for !(IE6,IE7)
        if (/\.css$/.test(href)) {
          // <link>
          w = _url.abs(v.href, absdir);
          !(w in _cache) && (_cache[w] = imports(_ajax.sync(w), _url.dir(w)));
          rv.push(_cache[w]);
        } else {
          // <style>
          rv.push(imports(v[prop1][prop2], absdir));
        }
      }
    }
  }
  // decode datauri
  //    <link href="data:text/css,...">
  if (_codec) {
    node = _doc.getElementsByTagName("link"), i = 0;
    while ( (v = node[i++]) ) {
      if (DATA_SCHEME_CSS.test(v.href)) {
        hash = _codec.decode(v.href);
        dstr = String.fromCharCode.apply(null, hash.data);
        w = "link" + i; // "link1"
        !(w in _cache) && (_cache[w] = imports(dstr, absdir));
        rv.push(_cache[w]);
      }
    }
  }
  return rv.join("");
};

// --- initialize ---

// --- export ---
_win.uuAltCSS.imports = _imports;

})(); // uuAltCSS.imports scope

